package com.sunyard.manage.controller;

import com.sunyard.constant.ErrMessageConst;
import com.sunyard.dal.bo.device.car.CarAuditBO;
import com.sunyard.dal.bo.device.car.CarDeleteBO;
import com.sunyard.dal.bo.PaginationBO;
import com.sunyard.dal.dto.CarCopyDTO;
import com.sunyard.dal.dto.CarCopyResltDTO;
import com.sunyard.dal.dto.CarDTO;
import com.sunyard.dal.dto.CarReslutDTO;
import com.sunyard.dal.entity.Car;
import com.sunyard.dal.entity.CarCopy;
import com.sunyard.enums.IsCheckEnum;
import com.sunyard.manage.service.CarService;
import com.sunyard.manage.util.ValidatorUtils;
import com.sunyard.utils.ExcelOutput;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import com.sunyard.utils.sm2.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: ZhangShuai
 * @description: 车辆信息控制层
 * @create: 2022-07-08 08:51
 **/

@Api(tags = "CarController", description = "车辆管理")
@Slf4j
@RestController
@RequestMapping(value = "/car", method = RequestMethod.POST)
public class CarController {
    @Autowired
    private CarService carService;

    @RequestMapping(value = "/deleteCar", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("删除车辆信息")
    public BaseResult deleteCar(@Validated @RequestBody CarDTO car, HttpServletRequest request) {
        try {
            return carService.delete(car, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/batchDeleteCar", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("批量删除车辆信息")
    public BaseResult batchDeleteCar(@Validated @RequestBody CarDeleteBO deleteBO, HttpServletRequest request) {
        try {
            return carService.batchDeleteCar(deleteBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/exportCar", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("车俩信息导出")
    public BaseResult exportKey(@RequestBody PaginationBO<CarDTO> queryBO, HttpServletRequest request, HttpServletResponse response) {
        try {
            return carService.exportCar(queryBO, request, response);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * 下载导入模板xls
     */
    @ApiOperation("下载导入模板xls")
    @PostMapping("/downloadTem")
    public void downloadTem(HttpServletResponse response) {

        String[] headers = new String[]{"车辆名称", "车牌号", "车辆所属机构号", "联系人电话", "联系人名称"};
        List<Object[]> dataList = null;
        // 防止中文乱码
        String headStr = null;
        OutputStream out = null;
        try {
            headStr = "attachment; filename=\"" + new String("customerMangerTemplate.xls".getBytes("utf8"), "ISO8859-1") + "\"";
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            ExcelOutput ex = new ExcelOutput("customerMangerTemplate.xls", headers, dataList);
            ex.export(out);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequestMapping(value = "/importInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("导入车辆数据")
    public BaseResult importInfo(HttpServletRequest request, @RequestParam("multipartFile") MultipartFile multipartFile) {
        try {
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            if (".xls".equals(suffix) || ".xlsx".equals(suffix)) {
                InputStream inputStream = multipartFile.getInputStream();
                HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
                HSSFSheet sheet = workbook.getSheetAt(0);
                if (sheet != null) {
                    List<CarDTO> addBOList = new ArrayList<>();
                    System.out.println(sheet.getLastRowNum() + "==============");
                    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                        CarDTO car = new CarDTO();
                        // 从第二行开始得到每行的值
                        HSSFRow row = sheet.getRow(i);
                        // /**
                        //  * sheet.getLastRowNum()不准确问题 20220919 tk
                        //  */
                        // HSSFCell cell = row.getCell(i);
                        // if (row == null || "".equals(cell.getStringCellValue())){
                        //     break;
                        // }
                        String carName = null;
                        if (row.getCell(0) != null) {
                            row.getCell(0).setCellType(CellType.STRING);
                            carName = row.getCell(0).getStringCellValue();
                        }
                        row.getCell(1).setCellType(CellType.STRING);
                        String carPlate = row.getCell(1).getStringCellValue();
                        row.getCell(2).setCellType(CellType.STRING);
                        String orgId = row.getCell(2).getStringCellValue();
                        row.getCell(3).setCellType(CellType.STRING);
                        String phone = row.getCell(3).getStringCellValue();
                        row.getCell(4).setCellType(CellType.STRING);
                        String phoneName = row.getCell(4).getStringCellValue();
                        //{"车辆名称", "车牌号", "车辆所属机构","联系人电话","审核状态", "联系人名称"};
                        car.setCarName(carName);
                        car.setOrgId(orgId);
                        car.setCarPlate(carPlate);
                        car.setContactPhone(phone);
                        car.setIsCheck(IsCheckEnum.PASS_CHECKED.getCode());
                        car.setContactName(phoneName);
                        car.setAdminId(opId);
                        addBOList.add(car);
                    }
                    int flag = 0;
                    String msg = null;
                    for (int i = 0; i < addBOList.size(); i++) {
                        try {
                            CarDTO carDTO = addBOList.get(i);
                            ValidatorUtils.beanValidate(carDTO);
                            BaseResult baseResult = carService.addCarInfo(carDTO, request);
                            if (!"00".equals(baseResult.getDataCode())) {
                                log.info("车辆信息导入错误信息={}", baseResult.getDataMessage());
                                flag++;
                                if (StringUtil.isEmpty(msg)) {
                                    msg = String.valueOf(i + 1);
                                } else {
                                    msg = msg + "," + (i + 1);
                                }
                            }
                        } catch (Exception e) {
                            log.error(ErrMessageConst.SYSTEM_ERROR, e);
                            log.info("车辆信息导入错误信息={}", e.getMessage());
                            flag++;
                            if (StringUtil.isEmpty(msg)) {
                                msg = String.valueOf(i + 1);
                            } else {
                                msg = msg + "," + (i + 1);
                            }
                        }
                    }
                    if (flag == 0) {
                        return GetResult.getResultSuccess("导入成功");
                    } else {
                        return GetResult.getResultFail("第" + msg + "条数据错误，导入失败");
                    }
                }
                return GetResult.getResultSuccess("导入成功");

            } else {
                return GetResult.getResultFail("文件类型只支持.xls 与.xlsx");
            }
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("分页查询车辆信息")
    public BaseResult<DataGrid<CarReslutDTO>> getLockByPage(@RequestBody PaginationBO<CarDTO> queryBO, HttpServletRequest request) {
        try {
            return carService.getCarByPage(queryBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/addCar", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("新增车辆信息")
    public BaseResult addCar(@Validated @RequestBody CarDTO car, HttpServletRequest request) {
        try {
            return carService.addCar(car, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/updateCar", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("修改车辆信息")
    public BaseResult<Car> updateCar(@Validated @RequestBody CarDTO car, HttpServletRequest request) {
        try {
            return carService.updateCar(car, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/auditCarInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("审核车辆信息")
    public BaseResult auditCarInfo(@Validated @RequestBody CarCopyDTO carCopy, HttpServletRequest request) {
        try {
            return carService.auditCarInfo(carCopy, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/batchAuditCarInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("批量审核车辆信息")
    public BaseResult batchAuditCarInfo(@Validated @RequestBody CarAuditBO carAuditBO, HttpServletRequest request) {
        try {
            return carService.batchAuditCarInfo(carAuditBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/queryAuditCar", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("查询审核车辆信息")
    public BaseResult<DataGrid<CarCopyResltDTO>> getCarCopyByPage(@RequestBody PaginationBO<CarCopyDTO> queryBO, HttpServletRequest request) {
        try {
            return carService.queryCarCopyByPage(queryBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/queryAuditInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("查询审核车辆详情")
    public BaseResult<Map<String, CarCopy>> queryAuditInfo(@RequestBody CarCopyDTO queryBO, HttpServletRequest request) {
        try {
            return carService.queryAuditInfo(queryBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @RequestMapping(value = "/queryCarByOrgId", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("通过机构号查询车辆信息")
    public BaseResult<List<Car>> queryCarByOrgId(@RequestBody CarDTO queryBO, HttpServletRequest request) {
        try {
            return carService.queryCarByOrgId(queryBO, request);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }
}
